package com.fuhao.pay.service;

import com.alibaba.fastjson.JSONObject;
import com.fuhao.core.base.BaseApiService;
import com.fuhao.core.base.BaseResponse;
import com.fuhao.core.twitter.SnowflakeIdUtils;
import com.fuhao.core.utils.GenerateToken;
import com.fuhao.dto.input.CreatePayTokenInputDto;
import com.fuhao.pay.entity.PaymentTransactionEntity;
import com.fuhao.pay.mapper.PaymentTransactionMapper;
import com.fuhao.pay.service.CreatePayTokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

/**
 * @author zhang
 * @title: 预支付接口实现类
 */
@RestController
public class CreatePayTokenServiceImpl extends BaseApiService<JSONObject> implements CreatePayTokenService {

    @Autowired
    private PaymentTransactionMapper paymentTransactionMapper;
    @Autowired
    private GenerateToken generateToken;

    @Override
    public BaseResponse<JSONObject> cratePayToken(@Valid CreatePayTokenInputDto createPayTokenInputDto, BindingResult bindingResult) {
        // 1.参数验证
        if (bindingResult.hasErrors()) {
            // 获取第一个错误!
            String errorMsg = bindingResult.getFieldError().getDefaultMessage();
            return setResultError(errorMsg);
        }
        PaymentTransactionEntity paymentTransactionEntity = new PaymentTransactionEntity();
        paymentTransactionEntity.setPayAmount(createPayTokenInputDto.getPayAmount());
        paymentTransactionEntity.setOrderId(createPayTokenInputDto.getOrderId());
        paymentTransactionEntity.setUserId(createPayTokenInputDto.getUserId());
        paymentTransactionEntity.setPaymentId(SnowflakeIdUtils.nextId());//通过雪花算法生产支付ID
        //插入预支付数据到支付交易表
        int result = paymentTransactionMapper.insertPaymentTransaction(paymentTransactionEntity);
        if(!toDaoResult(result)){
            return setResultError("系统错误");
        }
        // 获取主键id
        Long payId = paymentTransactionEntity.getId();
        if (payId == null) {
            return setResultError("系统错误!");
        }
        // 3.生成对应支付令牌
        String keyPrefix = "pay_";
        String token = generateToken.createToken(keyPrefix, payId + "");
        JSONObject dataResult = new JSONObject();
        dataResult.put("token", token);
        return setResultSuccess(dataResult);
    }
}
